package com.xuxueli.applyModules.commont;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xuxueli.applyModules.dto.EmailContentDto;
import com.xuxueli.applyModules.entity.User;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 模板替换字段
 */
@Component
public class InitEmaiContent {

    /**
     * 模板替换数据
     * @param emailContentDTO
     * @param groupInfo
     * @return
     */
    public String getServiceGroupTempleteContent(EmailContentDto emailContentDTO, User groupInfo){
        String value = StringUtils.EMPTY;
        if(null!=emailContentDTO){
            value = emailContentDTO.getContent();
            Map<String, Object> objectMap = object2Map(groupInfo);
            for (Map.Entry<String, Object> entry : objectMap.entrySet()) {
                if(value.contains("createTime") && "createTime".equals(entry.getKey())){
                    String str1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(groupInfo.getCreateTime());
                    value = value.replace("{createTime}", str1);
                }
                if(value.contains(entry.getKey())){
                    value = value.replace("{"+entry.getKey()+"}", entry.getValue().toString());
                }
            }
        }else{
            String str1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(groupInfo.getCreateTime());
            value = String.format("%s在%s申请上架服务%s，请尽快审批；",groupInfo.getCreateBy(),str1,groupInfo.getName());
        }
        return value;
    }

    /**
     * 对象转map，key=字段，value=值
     * @param obj
     * @return
     */
    public static Map<String, Object> object2Map(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 过滤数据
     * @param obj
     * @return
     */
    public Map<String, Object> objectToMap(Object obj,Map<String,String> stringMap) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                if(null!=stringMap && !stringMap.isEmpty()){
                    Set<String> stringSet = stringMap.keySet();
                    if(stringSet.contains(field.getName())){
                        map.put(field.getName(), field.get(obj));
                    }
                }else{
                    map.put(field.getName(), field.get(obj));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 对象转map,key=字段,value=说明
     * @param obj
     * @return
     */
    public Map<String, Object> objectToAnnotation(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                if(null!=annotation){
                    field.setAccessible(true);
                    map.put(field.getName(), annotation.value());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 测试数据
     * @param args
     */
    public static void main(String[] args) {
        InitEmaiContent initEmaiContent = new InitEmaiContent();
        String content = "{createBy}在{createTime}申请上架服务{name},所获金额为{amount}￥，请尽快审批；";
        System.out.println("最初数据模板："+content);
        User user = new User();
        user.setName("测试服务是否成功");
        user.setAmount(new BigDecimal("10000000000000000"));
        user.setCreateBy("猪猪");
        user.setCreateTime(LocalDateTime.now());
        EmailContentDto emailContentDTO = new EmailContentDto();
        emailContentDTO.setContent(content);
        String templeteContent = initEmaiContent.getServiceGroupTempleteContent(emailContentDTO,user);
        System.out.println("最终数据模板："+templeteContent);
        Map<String,String> annocations = new HashMap<>(16);
        annocations.put("name","名称");
        annocations.put("amount","金额");
        annocations.put("tempRemark","错误提示");
        Map<String, Object> stringObjectMap = initEmaiContent.object2Map(user);
        System.out.println("获取实体类字段对应值"+ JSONObject.toJSONString(stringObjectMap, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat));
        List<String> list = new ArrayList<>();
        for (String key:stringObjectMap.keySet()){
            if(!list.contains(key)){
                list.add(key);
            }
        }
        System.out.println("获取实体类字段"+JSONObject.toJSONString(list, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat));
        Map<String, Object> stringObjectMapAnnocation = initEmaiContent.objectToAnnotation(user);
        System.out.println("获取实体类字段对应说明"+JSONObject.toJSONString(stringObjectMapAnnocation, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat));
        System.out.println("待过滤数据："+JSONObject.toJSONString(annocations, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat));
        Map<String, Object> objectToMap = initEmaiContent.objectToMap(user, annocations);
        System.out.println("过滤获取实体类字段对应值"+JSONObject.toJSONString(objectToMap, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat));

    }



}
